<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 资源中心->角色信息
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="10">
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.roleCode" placeholder="角色编码" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-input v-model="query.data.roleName" placeholder="角色名称" class="handle-input"></el-input>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.roleType" placeholder="角色类型" class="handle-select" clearable>
                            <el-option v-for="item in roleTypeList"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :xs="24" :sm="12" :lg="6">
                        <el-select v-model="query.data.appCode" placeholder="所属应用" class="handle-select" clearable>
                            <el-option v-for="item in appList"
                                       :key="item.appCode"
                                       :label="item.appName"
                                       :value="item.appCode">
                                <span style="float: left">{{ item.appName }}</span>
                            </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="12" style="text-align: left">
                        <el-button type="primary" icon="el-icon-search" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :xs="24" :sm="12" style="text-align: right">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                        <el-button type="primary" icon="el-icon-refresh" @click="clearQueryForm">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table border class="table"
                      ref="multipleTable"
                      :data="tableData"
                      header-cell-class-name="table-header"
                      @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="角色ID" width="70"></el-table-column>
                <el-table-column prop="roleCode" label="角色编码" width="180" align="center"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleType" label="角色类型" align="center"></el-table-column>
                <el-table-column prop="appCode" label="所属应用" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center"></el-table-column>
                <el-table-column label="操作" width="130" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red"
                                   @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination background
                               layout="total, prev, pager, next"
                               :current-page="query.pageVo.pageNo"
                               :page-size="query.pageVo.pageSize"
                               :total="pageTotal"
                               @current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="角色信息管理" :visible.sync="editVisible" width="75%" :lock-scroll="false">
                <el-row :gutter="20" style="padding:15px 36px">
                    <el-col :span="14">
                        <el-form ref="form" :model="formData" label-width="70px">
                            <el-form-item label="角色编码">
                                <el-input v-model="formData.roleCode" placeholder="格式: 角色编码"></el-input>
                            </el-form-item>
                            <el-form-item label="角色名称">
                                <el-input v-model="formData.roleName" placeholder="角色名称"></el-input>
                            </el-form-item>
                            <el-form-item label="角色类型">
                                <el-radio-group v-model="formData.roleType">
                                    <el-radio-button v-for="item in roleTypeList" :label="item.value">
                                        {{ item.label }}
                                    </el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="所属应用">
                                <el-select v-model="formData.appCode" placeholder="资源所属应用编码" class="handle-select" clearable>
                                    <el-option v-for="item in appList"
                                               :key="item.appCode"
                                               :label="item.appName"
                                               :value="item.appCode">
                                        <span style="float: left">{{ item.appName }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="角色状态">
                                <el-radio-group v-model="formData.status">
                                    <el-radio-button v-for="item in statusList" :label="item.value">
                                        {{ item.label }}
                                    </el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="formData.remark"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="10">
                        <el-aside width="100%">
                            <el-row style="border: #97a8be solid 1px; min-height:360px; max-height:450px">
                                <div class="tree-container">
                                    <el-tree node-key="id"
                                             ref="tree"
                                             class="tree"
                                             show-checkbox
                                             highlight-current
                                             :indent="0"
                                             :check-strictly="true"
                                             :data="menuTree"
                                             :default-expanded-keys="expandKeys"
                                             :expand-on-click-node="false"
                                             :default-checked-keys="roleMenuTree"
                                             :props="defaultProps"
                                             @check-change="handleNodeCheck">
                                    </el-tree>
                                </div>
                            </el-row>
                        </el-aside>
                    </el-col>
                </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">保 存</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { OnionUtils } from '../../utils/onion-utils';
    import { listApp } from '../../api/appic/appInfo';
    import { fetchDictByIndex } from '../../api/resic/dictionary';
    import { doFindRole, doGetRole, doFindRoleMenuResource, doSaveRole, doDeleteRole } from '../../api/authic/role';
    import { doFindMenuResource } from '../../api/resic/menu';

    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    data:{
                        roleCode: '',
                        roleType: '',
                        appCode: ''
                    },
                    pageVo:{
                        pageNo: 1,
                        pageSize: 10
                    }
                },
                pageTotal: 0,
                editVisible: false,
                editRoleAuthVisible: false,
                formData: {},
                tableData: [],
                appList: [],
                statusList: [],
                roleTypeList: [],
                menuTree: [],
                roleMenuTree: [],
                expandKeys:[],
                id: -1,
                idx: -1,
                defaultProps: {
                    label: 'title',
                    children: 'subs'
                }
            };
        },

        //初始化页面数据
        created() {
            this.initData();
            this.findPage();
        },

        //方法区
        methods: {
            dateFormat(row,column){
                let data = row[column.property]
                if (data ===null) {
                    return ''
                }
                let dt = new Date(data)
                return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
            },

            //初始化页面数据
            initData(){
                fetchDictByIndex("onion.tenant.type,onion.role.type,onion.role.status").then(result => {
                    this.tenantTypeList = result.data["onion.tenant.type"];
                    this.roleTypeList = result.data["onion.role.type"];
                    this.statusList = result.data["onion.role.status"];
                });
                listApp().then(result => {
                    this.appList = result.data;
                });
            },

            //分页列表查询
            findPage(){
                doFindRole(this.query).then(result=>{
                    this.tableData = result.data.rows;
                    this.pageTotal = result.data.total || 0;
                })
            },

            //查询按钮事件
            handleQuery(){
                this.findPage();
            },

            //新增角色
            handleAdd(){
                this.idx = -1;
                this.formData ={"roleCode":"",
                                "roleType":"system",
                                "status":"enabled"}
                this.editVisible = true;
            },

            //编辑角色
            handleEdit(index, row) {
                if(index <= -1){
                    this.$alert("请选择一条记录!");
                    return;
                }else{
                    this.idx = index;
                    this.formData = row;
                    this.loadRoleAndTree(row.id);
                    this.editVisible = true;
                }
            },

            //打开角色权限配置
            handleAuthority(index, row){
                if(index <= -1){
                    this.$alert("请选择一条记录!");
                    return;
                }
                this.idx = index;
                this.formData = row;
                this.editVisible = true;
            },

            //保存角色
            handleSave(){
                //获取授权的菜单ID
                let selectNodeIds = this.$refs.tree.getHalfCheckedKeys().concat(this.$refs.tree.getCheckedKeys())
                let selectMenuIds = new Array();
                let selectResourceIds = new Array();
                for(let i=0; i<selectNodeIds.length; i++){
                    if(selectNodeIds[i].split(":").length == 2){
                        selectResourceIds.push(selectNodeIds[i]);
                    }else{
                        selectMenuIds.push(selectNodeIds[i]);
                    }
                }
                this.formData.menuIds = selectMenuIds;
                this.formData.resourceIds = selectResourceIds;
                //保存角色
                doSaveRole(this.formData).then(result => {
                    this.$message.success(`保存成功！`);
                    if(this.idx != -1){
                        this.$set(this.tableData, this.idx, result.data);
                    }else{
                        this.findPage();
                    }
                    this.editVisible = false;
                });
            },

            //删除角色
            handleDelete(index, row){
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    doDeleteRole(this.tableData[index].id).then(result => {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    });
                }).catch(() => {
                    this.$alert('异常！');
                });
            },

            //清空QueryForm
            clearQueryForm(){
                this.query.data = {};
            },

            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.findPage();
            },

            // 加载菜单树
            loadRoleAndTree(roleId){
                this.menuTree = [];
                this.roleMenuTree = [];
                if(!OnionUtils.isEmpty(roleId)){
                    doFindRoleMenuResource(roleId).then(result =>{
                        this.roleMenuTree = result.data;
                    })
                }
                if(!OnionUtils.isEmpty(this.formData.appCode)){
                    let paramData = {"appCode":this.formData.appCode};
                    doFindMenuResource(paramData).then(result =>{
                        this.menuTree = result.data;
                        this.expandKeys.length = 0;
                        this.expandKeys.push(this.menuTree[0].id);
                    })
                }
            },

            // 处理节点被选中
            handleNodeCheck(node, checked){
                let isChecked = false;
                if(checked && checked==true){
                    isChecked = true;
                }
                //子节点
                this.checkChildrenNode(node, isChecked);
                //父节点
                this.checkParentNode(node, isChecked);
            },

            // 设置父节点
            checkParentNode(node, checked){
                if(checked && checked==true && !OnionUtils.isEmpty(node) ){
                    let curNode = this.$refs.tree.getNode(node.id);
                    if(!OnionUtils.isEmpty(curNode) && !OnionUtils.isEmpty(curNode.parent)){
                        let pNode = curNode.parent.data;
                        this.checkParentNode(pNode, checked);
                        this.$refs.tree.setChecked(pNode.id, checked);
                    }
                }
            },

            // 设置孩子节点
            checkChildrenNode(node, checked){
                if(!OnionUtils.isEmpty(node)){
                    this.$refs.tree.setChecked(node.id, checked);
                    //处理子节点
                    if(node.subs && node.subs.length>0){
                        node.subs.forEach( curNode => {
                            this.checkChildrenNode(curNode, checked);
                        })
                    }
                }
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 10px;
    }

    .handle-select {
        width: 100%;
    }

    .handle-input {
        width: 100%;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    /* 树形结构节点添加连线 */
    .tree-container{

    }

    .tree-container /deep/ .el-tree > .el-tree-node:before {
        border-top: none;
    }

    .tree-container /deep/ .el-tree > .el-tree-node:after {
        border-top: none;
    }

    .tree /deep/ .el-tree-node {
        position: relative;
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node__children {
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node :last-child:before {
        height: 38px;
    }

    .tree /deep/ .el-tree > .el-tree-node:before {
        border-left: none;
    }

    .tree /deep/ .el-tree-node:before {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .tree /deep/ .el-tree-node__expand-icon.is-leaf {
        display: none;
    }

    .tree /deep/ .el-tree-node:before {
        border-left: 1px dashed #b8b9bb;
        bottom: 0px;
        height: 100%;
        top: -26px;
        width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        border-top: 1px dashed #b8b9bb;
        height: 20px;
        top: 12px;
        width: 24px;
    }

</style>